package cn.apthink.calendar;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import lombok.Getter;

public class WeekHelper {
	@Getter
	private final static Set<Week> weeks = new HashSet<Week>();

	/**
	 * 刷新周模板数据
	 * 
	 * @param lstWeekTemplateDetail
	 */
	public void refreshWeek(List<WeekTemplateDetail> lstWeekTemplateDetail) {
		weeks.clear();
		Set<String> ids = lstWeekTemplateDetail.stream().map(WeekTemplateDetail::getWeekId).collect(Collectors.toSet());
		ids.forEach(x -> {
			Week week = new Week();
			week.setId(x);
			List<WeekTemplateDetail> ws = lstWeekTemplateDetail.stream().filter(y -> {
				return y.getWeekId().equals(x);
			}).collect(Collectors.toList());
			Set<Integer> dis = ws.stream().map(WeekTemplateDetail::getDayIndex).collect(Collectors.toSet());
			for (Integer dayIndex : dis) {
				Day day = new Day();
				List<WeekTemplateDetail> wsd = ws.stream().filter(z -> {
					return z.getDayIndex() == dayIndex;
				}).collect(Collectors.toList());
				for (WeekTemplateDetail w : wsd) {
					TimeRange tr = DayTimeHelper.getTimeRange(w.getStartSecond(), w.getEndSecond(), w.isOvertime());
					day.addTimeRange(tr);
				}
				day = DayTimeHelper.getDay(day);
				week.setWeekDay(dayIndex, day);
			}
			weeks.add(week);
		});
	}

	/**
	 * 获取指定周模板数据
	 * 
	 * @param id
	 * @return
	 */
	public Week getWeek(String id) {
		Optional<Week> o = weeks.stream().filter(x -> {
			return x.getId().equals(id);
		}).findFirst();
		if (o.isPresent()) {
			return o.get();
		} else {
			throw new RuntimeException("周模板id不存在");
		}
	}
	
	public static WeekHelper testData() {
		WeekHelper helper = new WeekHelper();
    	helper.refreshWeek(WeekTemplateDetail.testDatas());
    	return helper;
	}
	
}
